# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
package Net::Tube::Filter::XSLT;

use Net::Tube;

our @ISA = qw(Net::Tube::Filter);

use XML::LibXSLT;
use XML::LibXML::Common qw(:w3c);

sub process {
    my $self   = shift;
    my $b      = $self->SUPER::process(@_);
    my ($xslt) = $self->get_config_entry('stylesheet-file');

    my $retval = $b;

    # create the XSLT processor only ONCE!
    my $xsl = $self->{XSLT_PROCESSOR};
    unless ( defined $xsl ) {
        if ( defined $xslt && length $xslt && -f $xslt && -r $xslt ) {
            my $xb = XML::LibXSLT->new();
            eval { $xsl = $xb->parse_stylesheet_file($xslt); };
            if ($@) {
                $xsl = undef;
            }
            else {
                $self->{XSLT_PROCESSOR} = $xsl;
            }
        }
    }

    if ( defined $xsl ) {
        $retval = $self->create_bucket();

        my $ns = $b->node_list;
        my @nodes;
        if ( defined $ns ) {
            @nodes = $ns->get_nodelist;
        }
        foreach my $n (@nodes) {
            if( $n->nodeType == DOCUMENT_NODE) {
		my $rd;
		eval { $rd = $xsl->transform($n); };
		if ( defined $rd && $rd->documentElement ) {
		    $retval->add_node($rd);
		    next; # OK done, move on
		}
	    }

	    # if the node was not transformed we add the original to
	    # the output bucket.
	    $retval->add_node($n);
        }
    }

    return $retval;
}

1;
